package com.fpost.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import net.sf.json.JSONObject;

import org.apache.struts.action.Action;

import com.fpost.action.MainAction;
import com.fpost.constants.ActionConstants;
import com.fpost.form.dto.ArticleDTO;
import com.fpost.util.ArticleUtils;
import com.fpost.util.DateUtil;

public class MyServlet extends HttpServlet {
	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
		
		System.out.println("In the doGet Method");
		
		String timeframeStr = (String) request.getParameter("timeframe");
        int timeframe = Integer.parseInt(timeframeStr);
        
        Calendar calendar = DateUtil.getGMTCalendar();
		switch(timeframe){
			case 1 : calendar.add(Calendar.MONTH, -1); break;
			case 3 : calendar.add(Calendar.MONTH, -3); break;
			case 6 : calendar.add(Calendar.MONTH, -6); break;
			case 12 : calendar.add(Calendar.MONTH, -12); break;
			case 0 : calendar.add(Calendar.YEAR, -12); break;
			default : calendar.add(Calendar.YEAR, -12); break;
 		}
		System.out.println("calendar date ("+timeframe+") = [" + calendar.getTime() + "]");
		
		java.sql.Date from = new java.sql.Date(calendar.getTimeInMillis());
		java.sql.Date to = new java.sql.Date(System.currentTimeMillis()); 
		
	    JSONObject json = new JSONObject();	    
	    try {
			List<ArticleDTO> list = ArticleUtils.getHighestRatingCurrentArticles(from, to, 100);
			json.put("list", list);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	    
	    response.setContentType("text/html; charset=UTF-8");
	    PrintWriter out = response.getWriter();
	    out.println(json);
	    out.flush();
    }
    
	public void init() throws ServletException {
        System.out.println("In the init() Method");
    }
 
    public void init(ServletConfig config) throws ServletException {
        System.out.println("In the init(ServletConfig config) Method");
        super.init(config);
    }
    

}
